import axios from 'axios';
import store from '../redux/store';

import {alertLogin} from '../components/common/alert';

const instance = axios.create({
    baseURL: `${process.env.REACT_APP_HOST}/api/`,
    timeout: 4000,
    headers: {'Content-Type': 'application/json'},
});

const invoke = async (url, method, data) => {

    const config = {url, method, data, headers: {}};

    const token = store.getState().auth.token;
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }
    if (method === 'PUT') {
        config.headers['Content-Type'] = 'multipart/form-data';
    }

    return new Promise((resolve, reject) => {
        instance(config)
            .then(response => {
                const {code, data, errmsg} = response.data;
                if (code === 200) {
                    resolve(data);
                } else {
                    reject(errmsg || `Error, code=${code}`);
                }
            })
            .catch(error => {
                if (error.response) {
                    // status code !== 200
                    if (error.response.status === 401) {
                        alertLogin();
                        return;
                    }
                    reject(`status=${error.response.status}, text=${error.response.statusText}`);
                } else if (error.request) {
                    reject(`${error.name}: code=${error.code}, message=${error.message}`);
                } else {
                    reject('Error in setting up the request');
                }
            });
    });
};

export const get = (url, data = null) => invoke(url, 'GET', data);
export const post = (url, data = null) => invoke(url, 'POST', data);
export const put = (url, data = null) => invoke(url, 'PUT', data);

